import 'package:flutter/material.dart';
import 'package:flutter_hsh/fluttergromore/ads/ads_utils.dart';
import 'package:flutter_hsh/utils/toast_utils.dart';
import 'package:get/get.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';

// 导入统一的任务模型
import '../jilu/jilu_logic.dart';

/// 添加清单页面控制器
class JiluAddLogic extends GetxController {
  // 选中的日期时间
  final Rx<DateTime> selectedDateTime = DateTime.now().obs;
  // 选中的时间字符串显示
  final RxString selectedTime = ''.obs;
  // 是否开启闹钟
  final RxBool hasAlarm = false.obs;
  // 任务类型（默认为待办事项）
  final Rx<TaskType> taskType = TaskType.todo.obs;
  
  @override
  void onInit() {
    super.onInit();
    // 初始化时设置默认时间显示
    updateSelectedTimeString();
  }

  // 显示日期时间选择器
  Future<void> showDateTimePicker(BuildContext context) async {
    // 先选择日期
    final DateTime? pickedDate = await showDatePicker(
      context: context,
      initialDate: selectedDateTime.value,
      firstDate: DateTime(2020),
      lastDate: DateTime(2030),
    );
    
    if (pickedDate != null) {
      // 再选择时间
      final TimeOfDay? pickedTime = await showTimePicker(
        context: context,
        initialTime: TimeOfDay.fromDateTime(selectedDateTime.value),
      );

      if (pickedTime != null) {
        // 合并日期和时间
        final newDateTime = DateTime(
          pickedDate.year,
          pickedDate.month,
          pickedDate.day,
          pickedTime.hour,
          pickedTime.minute,
        );
        
        selectedDateTime.value = newDateTime;
        updateSelectedTimeString();
        
        // 显示闹钟选择对话框
        _showAlarmDialog(context);
      }
    }
  }
  
  // 更新选中时间的字符串显示
  void updateSelectedTimeString() {
    final dt = selectedDateTime.value;
    selectedTime.value = '${dt.year}年${dt.month}月${dt.day}日 ${dt.hour.toString().padLeft(2, '0')}:${dt.minute.toString().padLeft(2, '0')}';
  }
  
  // 显示闹钟选择对话框
  void _showAlarmDialog(BuildContext context) {
    AdsUtils.showInterstitialAd();
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('闹钟设置'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: [
                const Text('开启闹钟提醒'),
                Switch(
                  value: hasAlarm.value,
                  onChanged: (value) {
                    hasAlarm.value = value;
                  },
                ),
              ],
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('确定'),
          ),
        ],
      ),
    );
  }
  
  // 保存任务
  void saveTask(String title, String note) {
    // 错误处理：标题验证
    if (title.isEmpty) {
      MyToast.show('请输入标题');
      return;
    }
    
    // 错误处理：时间验证
    if (selectedTime.value.isEmpty) {
      MyToast.show('请选择提醒时间');
      return;
    }
    
    try {
      // 显示加载中
      EasyLoading.show(status: '保存中...');
      
      // 获取主页面控制器
      final JiluLogic jiluLogic = Get.find<JiluLogic>();
      
      // 创建新的任务项
      final taskItem = TaskItem(
        id: DateTime.now().millisecondsSinceEpoch.toString(),
        title: title,
        note: note,
        dateTime: selectedDateTime.value,
        hasAlarm: hasAlarm.value,
        type: taskType.value,
        isCompleted: false,
      );
      
      // 添加到主页面任务列表
      jiluLogic.addTask(taskItem);
      
      // 显示成功提示
      MyToast.show('添加成功');
      
      // 隐藏加载中
      EasyLoading.dismiss();
      
      // 返回上一页
      Get.back();
    } catch (e) {
      // 错误处理
      EasyLoading.dismiss();
      MyToast.show('操作失败: ${e.toString()}');
    }
  }
  
  // 切换任务类型
  void toggleTaskType() {
    taskType.value = taskType.value == TaskType.todo ? TaskType.reminder : TaskType.todo;
  }
  
  // 设置任务类型
  void setTaskType(TaskType type) {
    taskType.value = type;
  }
}